﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Weibo4Sharp.Model;
using Newtonsoft.Json;

namespace Weibo4Sharp.Serialization.Converters
{
    internal class WeiboTagConverter : WeiboConverterBase
    {
        private const string TagTemplate = "{{ \"{0}\" : \"{1}\" }}";

        public override bool CanConvert(Type objectType)
        {
            var t = (IsNullableType(objectType))
                ? Nullable.GetUnderlyingType(objectType) : objectType;

            return typeof(WeiboTag).IsAssignableFrom(t);
        }

        public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
            {
                return null;
            }

            reader.Read();

            var id = Convert.ToInt64(reader.Value);

            reader.Read();

            var value = reader.Value.ToString();

            return new WeiboTag { Id = id, Value = value };
        }

        public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
        {
            if (!(value is WeiboTag))
            {
                return;
            }

            var tag = (WeiboTag)value;
            var json = string.Format(TagTemplate, tag.Id, tag.Value);
            writer.WriteValue(json);
        }
    }
}
